package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketStorage;
import com.cskaoyan.market.service.MarketStorageService;
import com.cskaoyan.market.service.MarketStorageServiceImpl;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@WebServlet("/admin/storage/*")
@MultipartConfig
public class AdminStorageController extends HttpServlet {
    private MarketStorageService marketStorageService=new MarketStorageServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/storage/", "");
        if ("list".equals(op)) {
            list(req, resp);
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/storage/", "");
        if ("create".equals(op)) {
            create(req, resp);
        } else if ("update".equals(op)) {
            update(req, resp);
        } else if ("delete".equals(op)) {
            delete(req, resp);
        }
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String reqBody = req.getReader().readLine();
        String id = JacksonUtil.parseString(reqBody, "id");
        MarketStorage marketStorage = new MarketStorage();
        assert id != null;
        marketStorage.setId(Integer.parseInt(id));
        marketStorageService.delete(marketStorage);
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok(marketStorage)));
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String reqBody = req.getReader().readLine();
        String id = JacksonUtil.parseString(reqBody, "id");
        String name = JacksonUtil.parseString(reqBody, "name");
        MarketStorage marketStorage = new MarketStorage();
        assert id != null;
        marketStorage.setId(Integer.parseInt(id));
        marketStorage.setName(name);
        marketStorage.setUpdateTime(LocalDateTime.now());
        marketStorageService.update(marketStorage);
        Object ok = ResponseUtil.ok(marketStorage);
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ok));
    }
    private void create(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //用户将图片提交到服务器后，解析图片
        Part part = req.getPart("file");
        String fileName = part.getSubmittedFileName();
        String contentType = part.getContentType();
        long size = part.getSize();
        String key= UUID.randomUUID()+"_"+fileName;
        ServletContext servletContext = getServletContext();
        String path = (String) servletContext.getAttribute("uploadPath");
        System.out.println(path);
        part.write(path+key);
        MarketStorage marketStorage = new MarketStorage();
        marketStorage.setDeleted(false);
        marketStorage.setAddTime(LocalDateTime.now());
        //创建的时候设定两个时间，后续更改的时候只需要设置update time即可
        marketStorage.setUpdateTime(LocalDateTime.now());
        //url可以存储http://localhost:8083/wx/storage/fetch/xxx.jpg，但是以这种形式存储到数据库有一个风险
        //如果后续你的ip地址、端口号改变了，那么图片便无法正常显示了，此时你的改动就比较大
        //此时可以在数据库中存储主机端口号后面的部分；接口要求返回的内容，后续在追加上
        String relativePath = "/wx/storage/fetch/" + key;
        marketStorage.setUrl(relativePath);
        marketStorage.setType(contentType);
        //key是最终的名称；name是上传的名字
        marketStorage.setKey(key);
        marketStorage.setName(fileName);
        marketStorage.setSize((int) size);
        //随后将要保存到数据库
        marketStorageService.create(marketStorage);
        //在这个地方再对url进行处理，追加上主机端口号
        //此时，经过数据库存储之后id便有了值，然后对url进行处理
        String url = marketStorage.getUrl();
        String domain = (String) servletContext.getAttribute("domain");
        marketStorage.setUrl(domain + url);
        //响应出去
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok(marketStorage)));
    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String pageParam = req.getParameter("page");
        String limitParam = req.getParameter("limit");
        String name = req.getParameter("name");
        String key = req.getParameter("key");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        Integer page = null;
        Integer limit = null;
        try {
            page = Integer.parseInt(pageParam);
            limit = Integer.parseInt(limitParam);
        } catch (NumberFormatException e) {
            Object object = ResponseUtil.badArgument();
            String s = JacksonUtil.getObjectMapper().writeValueAsString(object);
            resp.getWriter().println(s);
            return;
        }
        List<MarketStorage> marketStorageList = marketStorageService.list(limit, page, name, key, sort, order);
        //返回响应
        ServletContext servletContext = getServletContext();
        String domain = (String) servletContext.getAttribute("domain");
        for (MarketStorage marketStorage : marketStorageList) {
            marketStorage.setUrl(domain + marketStorage.getUrl());
        }
        Object o = ResponseUtil.okList(marketStorageList);
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(o));
    }
}
